<template>
  <div class="content_box">
    <div class="header_row flex align-center flex-wrap" v-if="hasBtn('EventPoster:query')">
      <div class="flex align-center m-r-2">
        <span class="tit_span nowarp">角色身份：</span>
        <el-select v-model="searchObj.Id" placeholder="请选择" clearable>
          <el-option v-for="item in userRole" :key="item.RoleName" :label="item.RoleName" :value="item.Id">
          </el-option>
        </el-select>
      </div>
      <div class="flex align-center m-r-2">
        <span>时间：</span>
        <el-date-picker v-model="searchObj.timeValue" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" clearable>
        </el-date-picker>
      </div>
      <el-button type="primary" @click="(searchObj.currentPage = 1), EventPosterGetListFun()">查询</el-button>
    </div>
    <div class="m-b-2 flex ju-bet">
      <el-button v-if="hasBtn('EventPoster:add')" @click="addActivity()" type="primary">新增活动</el-button>
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :max-height="tableHeight" :page-size="pageSize" :page-sizes="[10, 20, 50, 100, 200]" layout="total,sizes, prev, pager, next, jumper" :total="pageTotal">
      </el-pagination>
    </div>
    <div>
      <el-table class="m-b-1" :data="tableData" border stripe style="width: 100%" sortable="custom">
        <el-table-column prop="index" label="序号" align="center" fixed>
        </el-table-column>
        <el-table-column label="角色身份" align="center" fixed>
          <template slot-scope="scope">
            {{roleIdChangeFun(scope.row.RoleId)}}
          </template>
        </el-table-column>
        <el-table-column prop="EventName" label="活动类型" align="center" fixed>
        </el-table-column>
        <el-table-column prop="CreateDate" label="创建日期" align="center" fixed>
        </el-table-column>
        <el-table-column prop="UpdateDate" label="更新日期" align="center" fixed>
        </el-table-column>
        <el-table-column label="海报" align="center" fixed>
          <template slot-scope="scope">
            <img v-show="scope.row.Path" width="40px" height="40px" :src="scope.row.Path" alt="" @click="handlePictureCardPreview(scope.row.Path)">
            <div v-if="!scope.row.Path">暂无</div>
          </template>
        </el-table-column>
        <el-table-column label="是否有效" align="center" fixed>
          <template slot-scope="scope">
            <el-switch :disabled="!hasBtn('EventPoster:active')" v-model="scope.row.IsActive" @change="switchChange(scope.row.Id, scope.row.IsActive)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="220" fixed="right">
          <template slot-scope="scope">
            <el-button v-if="hasBtn('EventPoster:edit')" size="mini" @click="handleEdit(scope.$index, scope.row)" type="primary">编辑</el-button>

            <el-button v-if="hasBtn('EventPoster:delete')" size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="40%" :before-close="handleClose">
      <div class="flex m-b-2">
        <div class="titleName">
          <span>角色身份:</span>
        </div>
        <div class="titleInp activityDropdown">
          <el-select v-model="addObj.userRoleId" :disabled="dialogDis" placeholder="请选择">
            <el-option v-for="item in userRole" :key="item.RoleName" :label="item.RoleName" :value="item.Id">
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="flex m-b-2">
        <div class="titleName">
          <span>活动类型:</span>
        </div>
        <div class="titleInp">
          <el-select v-model="addObj.activityName" placeholder="请选择">
            <el-option v-for="item in activityList" :key="item.index" :label="item.Svalue" :value="item.Svalue">
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="flex m-b-2">
        <div class="titleName">
          <span>海报上传:</span>
        </div>
        <div class="flex m-l-1">
          <img width="70px" height="70px" v-show="form.Nameplate" :src="form.Nameplate" @click="handlePictureCardPreview(form.Nameplate)" alt="">
          <el-upload class="m-l-1" :action="upload" :headers="headerObj" ref="uploadBox" multiple :before-upload="beforeUploadFun" :limit="1" :auto-upload="true" accept=".jpg, .jpeg, .png" :show-file-list="false" :on-success="upLoadSuccess">
            <el-button size="small" type="primary">点击上传</el-button>
            <el-button size="small" type="warning" @click.stop="clearPath(),form.Nameplate = ''">移除</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传1张jpg/jpeg/png文件
            </div>
          </el-upload>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible2" width="50%">
      <img style="width: 100%" :src="addObj.dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
  import { GetUploadToken } from '@/api/ShareSetting/poster'
  import { getCodeMasterList } from '@/api/system/dictionary'
  import { getUserRole } from '@/api/system/user-role'
  import { EventPosterGetList, valid, eventPosterSave, eventPosterDelete } from '@/api/event-poster'
  export default {
    //import引入的组件需要注入到对象中才能使用
    name: '',
    components: {},
    data() {
      //这里存放数据
      return {
        dialogDis: false,
        tableData: [],
        pageTotal: 0,
        currentPage: 1,
        pageSize: 10,
        tableHeight: 0,
        dialogTitle: '',
        searchObj: [],
        userRole: [],

        addObj: {
          id: '',
          userRoleId: '',
          activityName: '',
          eventKey: ''
        },
        activityList: [],
        dialogVisible2: false,

        form: {
          SignIcon: '',
          Nameplate: ''
        },
        dialogVisible: false,
        upload: process.env.VUE_APP_UPLOAD_API + '/api/Tools/UploadFiles',
        headerObj: {
          Authorization: ''
        },
      };
    },
    props: {
    },
    //监听属性 类似于data概念
    computed: {
    },
    //监控data中的数据变化
    watch: {
    },
    //方法集合
    methods: {
      handleDelete(index, row) {
        this.$confirm('确认删除此条数据吗？').then(_ => {
          let obj = {
            Id: row.Id
          }
          eventPosterDelete(obj).then(res => {

            this.$notify({
              title: '删除成功',
              message: 'success',
              type: 'success',
              duration: 2000
            })
            this.tableData.splice(index, 1)
            this.pageTotal -= 1
          })
        })
      },
      handleEdit(index, row) {
        this.clearPath()
        this.dialogTitle = '编辑'
        this.addObj = {
          id: row.Id,
          userRoleId: row.RoleId,
          activityName: row.EventName,
          eventKey: row.eventKey
        }
        this.roleid = row.RoleId
        this.form.Nameplate = row.Path
        this.dialogVisible = true
        this.dialogDis = true
      },
      save() {
        if (!this.addObj.userRoleId) {
          this.$notify({
            title: '请选择角色身份',
            message: 'error',
            type: 'error',
            duration: 2000
          })
          return
        }
        if (!this.addObj.activityName) {
          this.$notify({
            title: '请选择活动类型',
            message: 'error',
            type: 'error',
            duration: 2000
          })
          return
        }
        let data = {
          "Id": this.addObj.id,
          "RoleId": this.addObj.userRoleId, //角色Id
          "EventKey": this.addObj.eventKey, //活动key
          "EventName": this.addObj.activityName, //活动名称
          "Path": this.form.Nameplate //海报地址
        }
        this.addObj.eventKey = this.geteventKeyFun()
        data.EventKey = this.addObj.eventKey
        if (this.dialogTitle == '新增') {
          data.Id = "00000000-0000-0000-0000-000000000000"
        }

        eventPosterSave(data).then(res => {
          this.$notify({
            title: '操作成功',
            message: 'success',
            type: 'success',
            duration: 2000
          })
          this.EventPosterGetListFun()
        }).catch()

        this.dialogVisible = false
      },
      geteventKeyFun() {
        let data = this.activityList.find(item => item.Svalue == this.addObj.activityName)
        return data.Skey
      },
      roleIdChangeFun(val) {
        let data = this.userRole.find(item => item.Id == val)
        if (data) {
          return data.RoleName
        } else {
          return "暂无"
        }
      },
      switchChange(id, IsActive) {
        valid({ Id: id }).then(_ => {
          this.$notify({
            title: '切换成功',
            message: 'success',
            type: 'success',
            duration: 2000
          })
          this.EventPosterGetListFun()
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.EventPosterGetListFun()
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.EventPosterGetListFun()
      },

      clearPath() {

        if (this.dialogTitle != '') {
          this.$refs.uploadBox.uploadFiles = []
        }
      },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => { });
      },
      handlePictureCardPreview(file) {
        //图片放大
        this.addObj.dialogImageUrl = file;
        this.dialogVisible2 = true;
      },
      addActivity() {
        this.clearPath()
        this.dialogTitle = '新增'
        this.addObj.userRoleId = ''
        this.addObj.activityName = ''
        this.form.Nameplate = ''
        this.dialogVisible = true
        this.dialogDis = false
      },
      async GetUploadTokenFun() {
        let { Data } = await GetUploadToken()
        this.headerObj.Authorization = Data || ''
      },
      async beforeUploadFun(e) {
        if (!this.headerObj.Authorization) {
          return false
        }
      },
      async EventPosterGetListFun() {

        let params = {
          "RoleId": "00000000-0000-0000-0000-000000000000", //角色Id
          "StartTime": null, //开始时间
          "EndTime": null, //结束时间
          "IsPaging": true, //是否分页
          "SortName": "CreateDate", //排序栏位
          "SortType": true, //排序类型｛True：正序；Flase：反序｝
          'PageIndex': this.currentPage,
          "PageSize": this.pageSize,
        }
        if (this.searchObj.Id) {
          params.RoleId = this.searchObj.Id
        }
        if (this.searchObj.timeValue) {
          params.StartTime = this.searchObj.timeValue[0]//开始时间
          params.EndTime = this.searchObj.timeValue[1]//结束时间
        }
        let { Data, PageIndex, Total } = await EventPosterGetList(params)
        if (!Data) {
          this.tableData = []
          this.pageTotal = 0
          return
        }
        let data = Data.map((item, index) => {
          for (let cell in item) {
            if (!item[cell] && this.$getType(item[cell]) !== 'Number') {
              item[cell] = '-'
            }
          }
          return { ...item, index: (index + 1) + ((PageIndex - 1) * 10) }
        })
        this.tableData = data
        this.pageTotal = Total
      },
      upLoadSuccess(res) {
        console.log('上传结束', res)
        console.log(this.$refs.uploadBox)
        if (res.code === 0) {
          // this.form.EquityPath = res.data.fileUrl
          this.$set(this.form, 'Nameplate', res.data.fileUrl)
        } else {
          if (this.sstimer) {
            clearTimeout(this.sstimer)
          }
          this.sstimer = setTimeout(() => {
            this.$notify({
              title: '上传失败',
              message: res.msg,
              type: 'warning',
              duration: 4500
            })
          }, 800)
        }
      },
      getActivityList() {
        let obj = {
          "SModule": "Wallet",
          "SFunction": "",
          "SKey": "",
          "SValue": "",
          "IsPaging": false, //是否分页
          "SortName": "CreateDate", //排序栏位
          "SortType": true //排序类型｛True：正序；Flase：反序｝
        }
        getCodeMasterList(obj).then(res => {
          for (let data of res.Data) {
            if (data.Svalue == '激活津贴' || data.Svalue == '达标津贴' || data.Svalue == '推广津贴') {
              this.activityList.push(data)
            }
          }
          for (let data of res.Data) {
            if (data.Svalue == '技术服务年费') {
              this.activityList.push(data)
            }
          }
          console.log('活动类型')
          console.log(this.activityList)
        }).catch(err => { })
      },
      getUserRolelist() {
        let userObj = {
          "RoleName": "", //身份角色名称
          "FilterRole": true, //是否过滤系统角色
          "FilterIns": false, //是否过滤机构角色
          "RoleMoney": 0, //身份角色金额
          "Platform": "PC", //平台类型：PC电脑、APP手机端、MP小程序
          "IsPaging": false, //是否分页
          "SortName": "PayAmount", //排序栏位
          "SortType": true //排序类型｛True：正序；Flase：反序｝
        }
        getUserRole(userObj).then(res => {
          this.userRole = res.Data
        }).catch(err => { })
      },
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {
      this.GetUploadTokenFun()
      this.getActivityList()
      this.getUserRolelist()
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {
      this.EventPosterGetListFun()
    },
    beforeCreate() { }, //生命周期 - 创建之前
    beforeMount() { }, //生命周期 - 挂载之前
    beforeUpdate() { }, //生命周期 - 更新之前
    updated() { }, //生命周期 - 更新之后
    beforeDestroy() { }, //生命周期 - 销毁之前
    destroyed() { }, //生命周期 - 销毁完成
    activated() { }, //如果页面有keep-alive缓存功能，这个函数会触发
  }
</script>
//@import url(); 引入公共css类
<style  scoped>
  .titleName {
    width: 25%;
    text-align: right;
    line-height: 40px;
    padding: 0 10px;
    font-size: 16px;
  }
  .titleInp {
    width: 50%;
  }
  .activityDropdown {
    line-height: 40px;
  }
  .ju-bet {
    justify-content: space-between;
  }
</style>